<?php

namespace app\api\controller;

use app\api\model\OauthOrder;
use app\api\service\WxPay;
use think\Controller;
use think\Request;
use think\facade\Log;
use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeAppPayRequest;
use Alipay\aop\request\AlipayTradePagePayRequest;
use app\api\model\Applepay AS ApplepayModel;
use app\common\controller\Send;
class Pay extends Controller
{
    
    use Send;
    /**
     * 微信小程序支付结果通知
     * https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function notify()
    {
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        Log::write($xml, 'wxPayNotifyXml');
        // 实例化微信支付
        $wxPay = new WxPay();
    
        if (empty($xml)) {
            $return = [
                'return_code' => 'FAIL',
                'return_msg' => ''
            ];
            echo $wxPay->toXml($return);
            exit;
        }
    
        // 实时写入报错信息
        Log::write($xml, 'wxPayNotify');
    
        $result = 'FAIL';
        $msg = '';
        if ($wxPay->notify($xml) === true) {
            $data = $wxPay->fromXml($xml);
            $totalFee = $data['total_fee'] / 100;
    
            // 支付回调处理
            $payResult = OauthOrder::orderPaid($data['openid'], $data['out_trade_no'], $totalFee, $data['attach'], '', $msg,null);
    
            // 实时写入报错信息
            Log::write($msg, 'wxPayMsg');
    
            if ($payResult) {
                $result = 'SUCCESS';
                $msg = 'OK';
            }
        }
    
        Log::write($msg, 'wxPayNotify');
    
        $return = [
            'return_code' => $result,
            'return_msg' => $msg
        ];
        echo $wxPay->toXml($return);
        exit;
    }
    /**
     * 微信app支付结果通知
     * https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function wxnotify()
    {
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input") ;
        //$this->debugLog($xml);
        Log::write($xml, 'wxPayNotifyXml');
        // 实例化微信支付
        $wxPay = new WxPay();
        
        if (empty($xml)) {
            $return = [
                'return_code' => 'FAIL',
                'return_msg' => ''
            ];
            echo $wxPay->toXml($return);
            exit;
        }

        // 实时写入报错信息
        Log::write($xml, 'wxPayNotify');
        
        $result = 'FAIL';
        $msg = '';
        if ($wxPay->notify($xml) === true) {
            $data = $wxPay->fromXml($xml);
            //$this->debugLog($data);
            $totalFee = $data['total_fee'] / 100;
            $orderSn   = $data['out_trade_no'];
            $attach   =  $data['attach'];
            // 支付回调处理
            $payResult = OauthOrder::orderNotify($orderSn,$attach,$data['transaction_id'],$totalFee);
            // 实时写入报错信息
            Log::write($msg, 'wxPayMsg');

            if ($payResult) {
                $result = 'SUCCESS';
                $msg = 'OK';
            }
        }

        Log::write($msg, 'wxPayNotify');

        $return = [
            'return_code' => $result,
            'return_msg' => $msg
        ];
        echo $wxPay->toXml($return);
        exit;
    }
    
    /**
     * 支付宝支付结果通知
     * https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function alinotify(Request $request){
            
            $info = $request->post();
            $aop = new AopClient;
            $aliPay = config('app.alipayconfig');
            $aop->alipayrsaPublicKey = $aliPay['rsaPublicKey'];
            $flag = $aop->rsaCheckV1($info,NULL,"RSA2");     //验签
            if(!$flag){
                echo 'fail';exit;
            }else if($info['trade_status']=='TRADE_SUCCESS'){     //支付状态
                // 支付回调处理
                $orderSn   = $info['out_trade_no'];
                $attach    = urldecode($info['passback_params']);
                $payMoney  = $info['total_amount'];
                OauthOrder::orderNotify($orderSn,$attach,$info['trade_no'],$payMoney);
                echo 'success';exit;
                
            }

    }
    
    
    /**
     * 苹果内购验证
     * @return array
     * @throws \think\Exception\DbException
     */
    public function appleNotify()
    {
        $reqData = input('');
        $return  = ApplepayModel::notify($reqData);
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }
    
    
    
   public  function debugLog($msg) {
        $fileName = "debug_" . date('Ymd', time()) . ".log";
        $this->writeLog($msg, $fileName);
    }
    
    
    
    public function writeLog($msg, $fileName) {
        $filePath = '/data/web/xyz.leaf-tech.net/logs/';
        $file = $filePath . $fileName;
        if (!file_exists($filePath)) {
            mkdir($filePath, '0777', true);
        }
        if (is_writable(dirname($file))) {
            if (!is_string($msg)) {
                $msg = var_export($msg, TRUE);
            }
            file_put_contents($file, "#" . date('Y-m-d H:i:s') . $msg . "\r\n", FILE_APPEND);
        }
    }
    
    
    
    
}